/**
 * 0. Project	: com.dnbns.bodywater 프로젝트
 *
 * 1. FileName	: MainActivity.java
 * 2. Package	: com.dnbns.bodywater
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 11. 15. 오전 10:49:15
 * 5. Comment	: 
 */

package com.dnbns.bodywater;

import java.util.Calendar;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dnbns.common.CommonAsyncTask;
import com.dnbns.common.StaticValue;
import com.dnbns.lib.CodeUtil;
import com.dnbns.lib.RbPreference;
import com.dnbns.network.NetworkChecker;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MainActivity extends Activity {

	private Context mContext;

	public static int count = 0;
    private boolean mIsBackButtonTouched = false;
	private View mDrinkView;
	private int mMaxHeight;
	
	private int mFullDrink;
	private float mWeight;
	private String mBirth;
	private boolean mSex;
	private float mDrink;
	
	private Button[] mDrinkWater;
	
	private boolean serverFlag = false;

	private AdView mAdView;
	private JSONArray mServerObjA;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        
        
		mAdView = (AdView) this.findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		mAdView.loadAd(adRequest);

        init();
    }

    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	getData();
    	getDBWater();
    	setDrinkView();
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
		mAdView.resume();
    }

	@Override
	public void onPause() {
		mAdView.pause();
		super.onPause();
	}

    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
		mAdView.destroy();
    	super.onDestroy();
    }
    
	
/**
 ***************************************************************
 * init
 ***************************************************************
 */

    private void init(){
    	mContext = this;
    	
    	mDrinkView = (View)findViewById(R.id.drink_bg);
		ImageView cup1 = (ImageView)findViewById(R.id.cup1);
		ImageView cup2 = (ImageView)findViewById(R.id.cup2);
		ImageView cup3 = (ImageView)findViewById(R.id.cup3);
		ImageView cup4 = (ImageView)findViewById(R.id.cup4);
		ImageView menu1 = (ImageView)findViewById(R.id.record);
		ImageView menu2 = (ImageView)findViewById(R.id.graph);
		ImageView menu3 = (ImageView)findViewById(R.id.map);
		ImageView menu4 = (ImageView)findViewById(R.id.setting);
    	
    	cup1.setOnClickListener(OCL);
    	cup2.setOnClickListener(OCL);
    	cup3.setOnClickListener(OCL);
    	cup4.setOnClickListener(OCL);
    	menu1.setOnClickListener(OCL);
    	menu2.setOnClickListener(OCL);
    	menu3.setOnClickListener(OCL);
    	menu4.setOnClickListener(OCL);
    	cup1.setOnTouchListener(OTL);
    	cup2.setOnTouchListener(OTL);
    	cup3.setOnTouchListener(OTL);
    	cup4.setOnTouchListener(OTL);
    	menu1.setOnTouchListener(OTL);
    	menu2.setOnTouchListener(OTL);
    	menu3.setOnTouchListener(OTL);
    	menu4.setOnTouchListener(OTL);

    	//현재 cup 이미지 높이 구하기.
    	final ImageView drink_cup = (ImageView)findViewById(R.id.drink_cup);
		final ViewTreeObserver obs = drink_cup.getViewTreeObserver();
		obs.addOnPreDrawListener(new OnPreDrawListener() {

			@Override
			public boolean onPreDraw() {
				mMaxHeight = drink_cup.getHeight();
				setDrinkView();
				// 1번만 동작하도록
				ViewTreeObserver obs = drink_cup.getViewTreeObserver();
				obs.removeOnPreDrawListener(this);
				return false;
			}
		});
		
		FrameLayout drink_layout = (FrameLayout)findViewById(R.id.drink_layout);
		drink_layout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent mIntent = new Intent(MainActivity.this, RecordActivity.class);
				startActivity(mIntent);
			}
		});
    }
    
/**
 ***************************************************************
 * Method
 ***************************************************************
 */
    
    //데이터 셋팅.
    private void getData(){

		RbPreference pref = new RbPreference(getApplicationContext());
		
		mWeight = Integer.valueOf(pref.getValue("weight", ""));
		mBirth = pref.getValue("birth", "");
		mSex = pref.getValue("sex", false);

    	TextView max_water = (TextView)findViewById(R.id.max_ml);
    	mDrinkWater = new Button[4];
    	
    	mDrinkWater[0] = (Button)findViewById(R.id.drink_1);
    	mDrinkWater[1] = (Button)findViewById(R.id.drink_2);
    	mDrinkWater[2] = (Button)findViewById(R.id.drink_3);
    	mDrinkWater[3] = (Button)findViewById(R.id.drink_4);
    	
    	mFullDrink = (int)(mWeight*2.2/2*30);
    	
    	//천자리 짜르기.
    	if(mFullDrink/100 != 0){
    		mFullDrink = (mFullDrink/100)*100;
    	}
    	
    	max_water.setText(mFullDrink+" ml");
    	mDrink = 0;
    	
    	for(int i=0; i<mDrinkWater.length; i++){
    		mDrinkWater[i].setText("0");
    	}
    }

    //먹은 양에 따른 ImageView 높이 조절
    private void setDrinkView(){
		//물양이 0일경우.
		if(mDrink == 0){
			mDrinkView.getLayoutParams().height = mMaxHeight;
			return;
		}

		if(mDrink >= mFullDrink){
			mDrinkView.getLayoutParams().height = 0;
		}else{
			int df = (int) ((mMaxHeight * mDrink)/mFullDrink);
			mDrinkView.getLayoutParams().height = mMaxHeight-df;
		}
    }
    
    //DB에서 데이터 select.
    private void getDBWater(){
    	JSONArray objA = CodeUtil.getInstance(mContext).getQuery("water");
		try {
	    	for(int i=0; i<objA.length(); i++){
	    		mDrink += objA.getJSONObject(i).getInt("cup_vol");
	    	}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(mDrink >= 9999){
			mDrink = 9999;
		}
		
		if(mDrink != 0){
			String sWeight = String.valueOf((int)mDrink);
			int j=sWeight.length()-1;
	    	for(int i=0; i<sWeight.length(); i++){
	    		mDrinkWater[i].setText(sWeight.charAt(j)+"");
	    		j--;
	    	}
		}
    }
    
    //DB에 데이터 Insert
    private void insertWater(int cup_type, int cup_vol){

    	ShowToast((int)mDrink);

		if(mDrink >= 9999){
			mDrink = 9999;
		}
		
		String sWeight = String.valueOf((int)mDrink);
		int j=sWeight.length()-1;
    	for(int i=0; i<sWeight.length(); i++){
    		mDrinkWater[i].setText(sWeight.charAt(j)+"");
    		j--;
    	}
    	
    	setDrinkView();

    	Calendar cal = Calendar.getInstance();
    	
		JSONArray jsonA = new JSONArray();
		JSONObject jsonO = new JSONObject();
		try {
			jsonO.put("weight", 	mWeight);
			jsonO.put("sex", 		mSex);
			jsonO.put("birth", 		mBirth);
			jsonO.put("cup_type", 	cup_type);
			jsonO.put("cup_vol", 	cup_vol);
			jsonO.put("year", 		cal.get(Calendar.YEAR));
			jsonO.put("month", 		cal.get(Calendar.MONTH)+1);
			jsonO.put("day", 		cal.get(Calendar.DAY_OF_MONTH));
			jsonO.put("hour", 		cal.get(Calendar.HOUR_OF_DAY));
			jsonO.put("minute", 	cal.get(Calendar.MINUTE));
			jsonO.put("second", 	cal.get(Calendar.SECOND));
			
			jsonA.put(jsonO);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			CodeUtil.getInstance(mContext).insertAllCode(jsonA, 1000);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    //DB에 데이터 Update
    private void updateWater(){
		try {
			CodeUtil.getInstance(mContext).updateAllCode(mServerObjA, 1000, "");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    private void ShowToast(int drink){
    	String temp = "";
    	if(drink >= 3000 && count == 0){
    		count++;
			temp = getResources().getString(R.string.drink3000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    	else if(drink >= 4000 && count == 1){
    		count++;
			temp = getResources().getString(R.string.drink4000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    	else if(drink >= 5000 && count == 2){
    		count++;
			temp = getResources().getString(R.string.drink5000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    	else if(drink >= 6000 && count == 3){
    		count++;
			temp = getResources().getString(R.string.drink6000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    	else if(drink >= 7000 && count == 4){
    		count++;
			temp = getResources().getString(R.string.drink7000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    	else if(drink >= 8000 && count == 5){
    		count++;
			temp = getResources().getString(R.string.drink8000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    	else if(drink >= 9000 && count == 6){
    		count++;
			temp = getResources().getString(R.string.drink9000);
	    	Toast.makeText(mContext, temp, Toast.LENGTH_LONG).show();
    	}
    }
    

/**
 ***************************************************************
 * Event
 ***************************************************************
 */

	//클릭 이벤트
    View.OnClickListener OCL = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.cup1:
				mDrink += StaticValue.CUP1;
				insertWater(1, StaticValue.CUP1);
				setWaterData();
				break;
			case R.id.cup2:
				mDrink += StaticValue.CUP2;
				insertWater(2, StaticValue.CUP2);
				setWaterData();
				break;
			case R.id.cup3:
				mDrink += StaticValue.CUP3;
				insertWater(3, StaticValue.CUP3);
				setWaterData();
				break;
			case R.id.cup4:
				mDrink += StaticValue.CUP4;
				insertWater(4, StaticValue.CUP4);
				setWaterData();
				break;
			case R.id.record:
				{
					Intent mIntent = new Intent(MainActivity.this, RecordActivity.class);
					startActivity(mIntent);
				}
				break;
			case R.id.graph:
				{
					Intent mIntent = new Intent(MainActivity.this, GraphActivity.class);
					startActivity(mIntent);
				}
				break;
			case R.id.map:
				{
					Intent mIntent = new Intent(MainActivity.this, MapActivity.class);
					startActivity(mIntent);
				}
				break;
			case R.id.setting:
				{
					Intent mIntent = new Intent(MainActivity.this, SettingActivity.class);
					startActivity(mIntent);
				}
				break;
			default:
				break;
			}
		}
	};
	
	//터치시 이미지 변경 이벤트
	View.OnTouchListener OTL = new View.OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			if(event.getAction() == MotionEvent.ACTION_DOWN){
				switch (v.getId()) {
				case R.id.cup1:
					((ImageView)v).setImageResource(R.drawable.cup1_on);
					break;
				case R.id.cup2:
					((ImageView)v).setImageResource(R.drawable.cup2_on);
					break;
				case R.id.cup3:
					((ImageView)v).setImageResource(R.drawable.cup3_on);
					break;
				case R.id.cup4:
					((ImageView)v).setImageResource(R.drawable.cup4_on);
					break;
				case R.id.record:
					((ImageView)v).setImageResource(R.drawable.menu_record_on);
					break;
				case R.id.graph:
					((ImageView)v).setImageResource(R.drawable.menu_graph_on);
					break;
				case R.id.map:
					((ImageView)v).setImageResource(R.drawable.menu_map_on);
					break;
				case R.id.setting:
					((ImageView)v).setImageResource(R.drawable.menu_setting_on);
					break;
				}
			}else if(event.getAction() == MotionEvent.ACTION_UP){
				switch (v.getId()) {
				case R.id.cup1:
					((ImageView)v).setImageResource(R.drawable.cup1);
					break;
				case R.id.cup2:
					((ImageView)v).setImageResource(R.drawable.cup2);
					break;
				case R.id.cup3:
					((ImageView)v).setImageResource(R.drawable.cup3);
					break;
				case R.id.cup4:
					((ImageView)v).setImageResource(R.drawable.cup4);
					break;
				case R.id.record:
					((ImageView)v).setImageResource(R.drawable.menu_record);
					break;
				case R.id.graph:
					((ImageView)v).setImageResource(R.drawable.menu_graph);
					break;
				case R.id.map:
					((ImageView)v).setImageResource(R.drawable.menu_map);
					break;
				case R.id.setting:
					((ImageView)v).setImageResource(R.drawable.menu_setting);
					break;
				}
				
			}
			return false;
		}
	};
	

/**
 * =================================================================================
 * 서버연동
 * =================================================================================
 */

	//먹은 물 연동.
	private void setWaterData() {
		
		if(serverFlag){
			return;
		}
		
		serverFlag = true;
		
		NetworkChecker nc = new NetworkChecker();
		if(!nc.isUseNetwork(mContext, this)){
			return;
		}

		Locale systemLocale = getResources().getConfiguration().locale;
    	mServerObjA = CodeUtil.getInstance(mContext).getQuery("water2");

		JSONObject json = new JSONObject();
		try {
			json.put("url", StaticValue.URL+StaticValue.FR_1002);

			JSONObject jsonO = new JSONObject();
			jsonO.put("m_device", 		"android");
			jsonO.put("m_country", 		systemLocale.getCountry());
			jsonO.put("m_language", 	systemLocale.getLanguage());
			jsonO.put("water_data", 	mServerObjA);
			
			json.put("params", jsonO);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//서버통신
		CommonAsyncTask.getInstance(mContext, mHandler).getWaterDataTask(json);
	}

/**
 * =================================================================================
 * Handler
 * =================================================================================
 */

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			//서버전송완료
			case 1:
				updateWater();
				serverFlag = false;
				break;
			//서버전송실패
			case 9999:
				serverFlag = false;
				break;
			}
		}
	};

    @Override
    public void onBackPressed() {
        if (mIsBackButtonTouched == false) {
            mIsBackButtonTouched = true;
            Toast.makeText(mContext, "한 번 더 누르시면 종료됩니다.", Toast.LENGTH_SHORT).show();
        }
 
        else if (mIsBackButtonTouched == true) {
            finish();
        }
    }
}
